package org.setamv.springcloud.hystrix.raw.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 测试Hystrix超时回退的命令
 */
public class FallbackHystrixCommand extends HystrixCommand<String> {

    public FallbackHystrixCommand() {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                     // 设置超时时间为3秒（默认为1秒）
                    .withExecutionTimeoutInMilliseconds(3000))
        );
    }

    private Long startTime;

    @Override
    protected String run() throws Exception {
        // 记录开始执行时间
        startTime = System.currentTimeMillis();

        // 使用HttpClient访问URL
        // 下面的接口在服务器会固定等待10秒，Hystrix会在接口调用返回之前就中断等待。
        String url = "http://setamv.tech:9091/greetings/from/setamv/slowly";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpGet);
        String greetings = EntityUtils.toString(response.getEntity());
        return greetings;
    }

    /**
     * 定义接口访问超时后的返回值
     */
    @Override
    protected String getFallback() {
        long endTime = System.currentTimeMillis();
        return "timeout from server after " + (endTime - startTime) + "(ms).";
    }
}
